﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RungSoft.RungEBookMaker.Providers.DocFormater.Umd;
using RungSoft.RungEBookMaker.Providers;

namespace RungSoft.RungEBookMaker.Controls.Panels
{
    internal partial class pnEBookMaker : UserControl
    {
        private BookBM mBookBM = new BookBM();
        private WriteInfo mWriteInfo;

        internal pnEBookMaker()
        {
            InitializeComponent();
        }

        internal pnEBookMaker(WriteInfo infoWriter)
            : this()
        {
            this.mWriteInfo = infoWriter;
        }

        private void pnEBookMaker_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;

            this.cbBookType.Items.Add(RungSoft.RungEBookMaker.Providers.DocFormater.Umd.StaticFunctions.BookTypeText.BOOK_TYPE_TEXT);
            this.cbBookType.Items.Add(RungSoft.RungEBookMaker.Providers.DocFormater.Umd.StaticFunctions.BookTypeText.BOOK_TYPE_CARTTON);
            this.cbBookType.Items.Add(RungSoft.RungEBookMaker.Providers.DocFormater.Umd.StaticFunctions.BookTypeText.BOOK_TYPE_COMIC_BOOK);
            this.cbBookType.SelectedIndex = 0;
            this.ttbFilePath.Text = @"C:\Users\rungroo\Desktop\aa.umd";
        }

        #region 菜单操作
        /// <summary>
        /// 
        /// </summary>
        private void btnMenuAdd_Click(object sender, EventArgs e)
        {
            string title = txbChapterTitle.Text.Trim();
            string content = txbContent.Text.Trim();

            if (string.IsNullOrEmpty(title))
            {
                this.mWriteInfo("待添加的章节标题不能为空。", InfoType.Warning);
                return;
            }
            else if (string.IsNullOrEmpty(content))
            {
                this.mWriteInfo("待添加的章节内容不能为空。", InfoType.Warning);
                return;
            }
            else if (this.mBookBM.Chapters.Find(delegate(ChapterBM bm) { return bm.Title == title; }) != null)
            {
                this.mWriteInfo("标题不能重复。", InfoType.Warning);
                return;
            }

            ChapterBM cBM = new ChapterBM(title, content);

            mBookBM.AppendChapter(cBM);
            lbMenu.Items.Add(cBM);

            this.mWriteInfo(string.Format("添加章节【{0}】，正文{1}字。", cBM.Title, cBM.Content.Length), InfoType.Success);
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (lbMenu.SelectedIndex < 0) return;

            ChapterBM cBM = lbMenu.SelectedItem as ChapterBM;
            if (cBM != null)
            {
                this.mBookBM.RemoveChapter(cBM);
                lbMenu.Items.RemoveAt(lbMenu.SelectedIndex);

                this.mWriteInfo(string.Format("删除章节【{0}】。", cBM.Title), InfoType.Success);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnChapterUp_Click(object sender, EventArgs e)
        {
            if (lbMenu.SelectedIndex <= 0) return;

            this.MoveListBoxItem(lbMenu, lbMenu.SelectedItem, -1);
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnChapterDown_Click(object sender, EventArgs e)
        {
            if (lbMenu.SelectedIndex < 0) return;
            if (lbMenu.SelectedIndex == lbMenu.Items.Count - 1) return;

            this.MoveListBoxItem(lbMenu, lbMenu.SelectedItem, 1);
        }

        /// <summary>
        /// （重新）绑定章节菜单的数据。
        /// </summary>
        private void lbMenu_Bind()
        {
            this.lbMenu.Items.Clear();

            foreach (ChapterBM cBM in this.mBookBM.Chapters)
                this.lbMenu.Items.Add(cBM);
        }

        /// <summary>
        /// 移动菜单项
        /// </summary>
        /// <param name="lb">菜单列表控件</param>
        /// <param name="item">待移动项</param>
        /// <param name="step">移动步长</param>
        private void MoveListBoxItem(ListBox lb, object item, int step)
        {
            string title = item.ToString();
            int index = this.mBookBM.Chapters.FindIndex(delegate(ChapterBM bm) { return bm.Title == title; });
            if (index >= 0)
            {
                ChapterBM cBM = this.mBookBM.Chapters[index];
                ChapterBM downBM = this.mBookBM.Chapters[index + step];
                cBM.Index = cBM.Index + step;
                downBM.Index = downBM.Index - step;

                this.mBookBM.Chapters.Sort(delegate(ChapterBM x, ChapterBM y) { return x.Index - y.Index; });

                this.lbMenu_Bind();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void btnChapterClear_Click(object sender, EventArgs e)
        {
            this.mBookBM.Chapters.Clear();
            this.lbMenu.Items.Clear();
            this.txbChapterTitle.Text = this.txbContent.Text = string.Empty;

            this.mWriteInfo("清除本书所有章节。", InfoType.Success);
        }

        /// <summary>
        /// 
        /// </summary>
        private void lbMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbMenu.SelectedIndex < 0) return;

            string title = lbMenu.SelectedItem.ToString();
            txbChapterTitle.Text = title;
            txbContent.Text = this.mBookBM.Chapters.Find(delegate(ChapterBM bm) { return bm.Title == title; }).Content;
        }
        #endregion

        // 浏览
        private void btnBrowseFile_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                sfd.Filter = "UMD文件|*.umd";
                sfd.AddExtension = true;

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    ttbFilePath.Text = sfd.FileName;
                }
            }
        }

        // 保存
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (mBookBM.Chapters.Count == 0)
            {
                this.mWriteInfo("章节数为0，无法生成。", InfoType.Warning);
            }
            else
            {
                this.FillBookBM();

                UmdFormater.WriteUMDBook(mBookBM);
                this.mWriteInfo("保存书籍成功。", InfoType.Success);
            }
        }

        // 保存工程
        private void btnSaveProject_Click(object sender, EventArgs e)
        {
            this.FillBookBM();

            try
            {
                this.mBookBM.SaveAsProject("Project");
                this.mWriteInfo("保存工程成功。", InfoType.Success);
            }
            catch (Exception ex)
            {
                this.mWriteInfo("保存工程失败：" + ex.Message, InfoType.Errer);
            }
        }

        // 载入工程
        private void btnLoadProject_Click(object sender, EventArgs e)
        {
            this.FillBookBM();

            try
            {
                this.mBookBM.LoadByProject("Project");

                this.mWriteInfo("载入工程成功。", InfoType.Success);
                this.RenderByBookBM();
            }
            catch (Exception ex)
            {
                this.mWriteInfo("载入工程失败：" + ex.Message, InfoType.Errer);
            }
        }

        // 将界面控件中的值赋予 mBook 变量。
        private void FillBookBM()
        {
            mBookBM.Title = tbBookTitle.Text.Trim();
            mBookBM.Author = tbAuthor.Text.Trim();
            mBookBM.FilePath = ttbFilePath.Text;
            mBookBM.Publisher = tbPublisher.Text.Trim();
            mBookBM.Vendor = tbVendor.Text.Trim();
            mBookBM.Kind = tbGender.Text.Trim();
            #region BookType
            if (this.cbBookType.SelectedIndex == 0)
            {
                this.mBookBM.Formate = RungSoft.RungEBookMaker.Providers.DocFormater.Umd.StaticFunctions.BookType.BOOK_TYPE_TEXT;
            }
            else if (this.cbBookType.SelectedIndex == 1)
            {
                this.mBookBM.Formate = RungSoft.RungEBookMaker.Providers.DocFormater.Umd.StaticFunctions.BookType.BOOK_TYPE_CARTTON;
            }
            else if (this.cbBookType.SelectedIndex == 2)
            {
                this.mBookBM.Formate = RungSoft.RungEBookMaker.Providers.DocFormater.Umd.StaticFunctions.BookType.BOOK_TYPE_COMIC_BOOK;
            }
            #endregion
        }

        // 将 mBook 变量中的值赋予界面控件。
        private void RenderByBookBM()
        {
            tbAuthor.Text = this.mBookBM.Author;
            tbBookTitle.Text = this.mBookBM.Title;
            tbGender.Text = this.mBookBM.Kind;
            tbPublisher.Text = this.mBookBM.Publisher;
            tbVendor.Text = this.mBookBM.Vendor;

            lbMenu.Items.Clear();
            foreach (ChapterBM bm in this.mBookBM.Chapters)
            {
                lbMenu.Items.Add(bm);
            }
        }
    }
}
